<script setup>
import { ref } from "vue";
import {
  CARD_KIND,
  CARD_WIDTH,
  CARD_HEIGHT,
  initDefaultCardInfos,
  initJsonCardInfos,
  initManageredCardInfos,
} from "./card-factory";

// 可操作的卡片
const cardInfos = ref([]);
// 持有的卡片
const holdCardInfos = ref([]);
// 游戏是否结束
let isGameOver = false;

/**
 * 刷新卡片的样式（白色可点击、灰色不可点击）
 */
function findAndChangeBottom() {
  console.log("cardInfos.value.legnth", cardInfos.value.length);
  cardInfos.value.forEach((aimCard) => {
    const coverCardInfo = cardInfos.value.find((item) =>
      isCovered(aimCard, item)
    );
    if (coverCardInfo) setCardBottom(aimCard);
    else setCardNormal(aimCard);
  });
}
/**
 * 判断是否被覆盖了
 * @param {*} bottomCard
 * @param {*} topCard
 */
function isCovered(bottomCard, topCard) {
  if (bottomCard.level >= topCard.level) return false;
  const isXFit = Math.abs(topCard.x - bottomCard.x) < CARD_WIDTH;
  const isYFit = Math.abs(topCard.y - bottomCard.y) < CARD_HEIGHT;
  return isXFit && isYFit;
}
/**
 * 如果被覆盖了，则设置为灰色不可点击
 * @param {*} card
 */
function setCardBottom(card) {
  card.isBottom = true;
  card.cardClass = ["card card-bottom"];
}
/**
 * 如果没有被覆盖，则设置为白色可点击
 * @param {*} card
 */
function setCardNormal(card) {
  card.isBottom = false;
  card.cardClass = ["card"];
}

function OnCardClick(id) {
  if (isGameOver) {
    alert("game over, please F5");
    return;
  }
  console.log("cardClick, id:", id);
  const index = cardInfos.value.findIndex((item) => item.id === id);
  if (index < 0) {
    console.error("click a unknown card:", id);
    return;
  }
  // 底层的不能点击
  if (cardInfos.value[index].isBottom) {
    return;
  }
  // 将卡片加入到手卡中
  holdCardInfos.value.push({ ...cardInfos.value[index] });
  // 移除卡片
  cardInfos.value.splice(index, 1);
  dealHoldCards();
  if (isGameOver) return;
  if (isGameSuccess()) return;
  findAndChangeBottom();
}
/**
 * 处理手牌；判断游戏失败
 */
function dealHoldCards() {
  if (holdCardInfos.value.length < 3) return;
  const content = findSameThreeCards();
  // 如果找到了相同的三个卡片，移除它们
  if (content >= 0) {
    const sameIndex1 = holdCardInfos.value.findIndex(
      (item) => item.content === content
    );
    holdCardInfos.value.splice(sameIndex1, 1);
    const sameIndex2 = holdCardInfos.value.findIndex(
      (item) => item.content === content
    );
    holdCardInfos.value.splice(sameIndex2, 1);
    const sameIndex3 = holdCardInfos.value.findIndex(
      (item) => item.content === content
    );
    holdCardInfos.value.splice(sameIndex3, 1);
  }

  if (holdCardInfos.value.length === 8) {
    isGameOver = true;
    alert("game over, please F5");
    return;
  }
}

function findSameThreeCards() {
  const holdMap = new Map();
  for (let index = 0; index < holdCardInfos.value.length; index++) {
    const element = holdCardInfos.value[index];
    const contentCount = holdMap.get(element.content);
    if (!contentCount) {
      holdMap.set(element.content, 1);
      continue;
    }
    if (contentCount === 2) return element.content;
    else holdMap.set(element.content, contentCount + 1);
  }
}
/**
 * 判断游戏是否结束
 */
function isGameSuccess() {
  if (cardInfos.value.length === 0) {
    alert("老铁 666");
    return true;
  }
}

const origionCardInfos = initDefaultCardInfos();
// const origionCardInfos = initJsonCardInfos()
console.log("origionCardInfos", origionCardInfos);
cardInfos.value.push(...origionCardInfos);
findAndChangeBottom();

// #region 切换游戏数据（随机卡片，还是读取json中的卡片）
function RandomClick() {
  cardInfos.value = []
  holdCardInfos.value = []
  const origionCardInfos = initDefaultCardInfos();
  console.log("origionCardInfos", origionCardInfos);
  cardInfos.value.push(...origionCardInfos);
  findAndChangeBottom();
}
function ReadJsonClick() {
  cardInfos.value = []
  holdCardInfos.value = []
  const origionCardInfos = initJsonCardInfos();
  console.log("origionCardInfos", origionCardInfos);
  cardInfos.value.push(...origionCardInfos);
  findAndChangeBottom();
}
function ReadManageredClick() {
  cardInfos.value = []
  holdCardInfos.value = []
  const origionCardInfos = initManageredCardInfos();
  console.log("origionCardInfos", origionCardInfos);
  if (origionCardInfos.length === 0) {
    alert('no data! please click [show manager page] to manage the data first')
  }
  cardInfos.value.push(...origionCardInfos);
  findAndChangeBottom();
}
// #endregion
</script>

<template>
  <div>
    <div>
      <button @click="RandomClick">Random Game</button>
      <button @click="ReadJsonClick">ReadJson Game</button>
      <button @click="ReadManageredClick">Managered Game</button>
    </div>
    <!-- 标题 -->
    <span class="title">数了个数</span>
    <!-- 持有的 8个 卡片 -->
    <div class="hold-cards-layout">
      <div v-for="cardInfo in holdCardInfos" class="hold-card">
        {{ cardInfo.content }}
      </div>
    </div>
    <!-- 堆叠的主卡片们 -->
    <div id="mainLayout" style="margin-top: 20px; margin-left: 70px">
      <div v-for="cardInfo in cardInfos" :class="cardInfo.cardClass" @click="OnCardClick(cardInfo.id)"
        :style="cardInfo.translateStyle">
        {{ cardInfo.content }}
      </div>
    </div>
  </div>
</template>
<style>
@import "./style/card.css";

/* 定义变量 */
:root {
  --cardWidth: 70px;
  --cardHeight: 70px;
  --cardFontSize: 35px;
}

body {
  background-color: lightgreen;
  margin: 0 !important;
}

.title {
  color: rgb(93, 90, 90);
  font-size: 48px;
  margin: 0 auto;
  text-align: center;
  height: 100vh;
  margin-left: 36px;
}

.hold-cards-layout {
  display: flex;
  flex-direction: row;
  border: 1px solid darkorange;
  align-items: center;
  height: calc(var(--cardHeight) + 20px);
  width: calc(var(--cardWidth) * 8 + 30px);
  padding-bottom: 10px;
  padding-left: 14px;
}

.hold-card {
  width: var(--cardWidth);
  height: var(--cardHeight);
  border-radius: 4px;
  background-color: white;
  color: black;
  font-size: var(--cardFontSize);
  box-shadow: 0 8px 0 green;
  text-align: center;
  line-height: var(--cardHeight);
  border: 1px solid lightgreen;
  cursor: default;
}
</style>
